#pragma once

#include <thread>
#include <iostream>
#include <windows.h>
#include <array>
#include <vector>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <commctrl.h>
#include <ranges>
#include <future>


template<typename F>
auto unpackFun([[maybe_unused]] F func) {
    return [&](auto t) { return std::apply(func, t); };
}

template<size_t N>
class ThreadPool {
public:
    using Task = std::function<void()>;

    ThreadPool() {
        for (auto &t: workers) {
            t = std::thread([this] {
                while (true) {
                    std::unique_lock<std::mutex> lock(mtx);
                    condition.wait(lock, [this] { return stop || !tasks.empty(); });
                    if (stop && tasks.empty()) {
                        return;
                    }
                    Task task = std::move(tasks.front());
                    tasks.pop();
                    lock.unlock();
                    task();
                }
            });
        }
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(mtx);
            stop = true;
        }
        condition.notify_all();
        for (std::thread &worker: workers) {
            worker.join();
        }
    }

    [[maybe_unused]] void enqueue(Task task) {
        {
            std::unique_lock<std::mutex> lock(mtx);
            tasks.emplace(std::move(task));
        }
        condition.notify_one();
    }

    template<typename F, typename...Args>
    requires (sizeof...(Args) >= 1)
    void enqueue([[maybe_unused]] F func, [[maybe_unused]] Args...args) {
        enqueue([=]() { func(args...); });
    }

    template<typename F, typename It>
    requires std::ranges::range<It> &&
             std::invocable<F, std::ranges::range_value_t<It>>
    void each(F func, const It &it) {
        for (const auto &x: it) {
            enqueue(func, x);
        }
    }

    template<typename F, typename It>
    requires std::ranges::range<It> &&
             std::invocable<F, std::ranges::range_value_t<It>>
    auto map(F func, const It &it) {
        using R = std::invoke_result_t<F, std::ranges::range_value_t<It>>;
        std::vector<std::shared_ptr<std::promise<R>>> res(std::ranges::size(it));

        for (const auto &[i, x]: it | std::views::enumerate) {
            auto promise = std::make_shared<std::promise<R>>();
            res[i] = promise;
            enqueue([=]() {
                try {
                    promise->set_value(func(x));
                } catch (const std::exception_ptr &e) {
                    promise->set_exception(e);
                }
            });
        }
        return res;
    }

private:
    std::array<std::thread, N> workers;
    std::queue<Task> tasks;
    std::mutex mtx;
    std::condition_variable condition;
    bool stop = false;
};
